package com.hsmw.api.controller.biz;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.mapper.*;
import com.hsmw.api.service.*;
import com.hsmw.api.vo.*;
import com.hsmw.common.base.BaseController;
import com.hsmw.common.base.BasePage;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.hsmw.api.utils.CommonUtils;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.form.GetObjectByIdForm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author WD
 */
@Api(tags = "BIZ-项目审核管理")
@RestController
@RequestMapping("/api/item")
public class BizItemController extends BaseController<HsmwAuditService, HsmwAudit> {

	@Autowired
	private HsmwItemService hsmwItemService;


	@Autowired
	private HsmwVehicleService hsmwVehicleService;


	@Autowired
	private HsmwLeasingCompanyService hsmwLeasingCompanyService;



	@Autowired
	private HsmwOrderService hsmwOrderService;

	@Autowired
	private HsmwConcretePlantInfoService hsmwConcretePlantInfoService;


	@Autowired
	private HsmwForcemanItemMapper hsmwForcemanItemMapper;

	@Autowired
	private CurrentHsmwUserUtils currentHsmwUserUtils;



	@Autowired
	private HsmwPmUserService hsmwPmUserService;

	@Autowired
	private HsmwConcreteUserService hsmwConcreteUserService;

	@Autowired
	private HsmwDriverUserService hsmwDriverUserService;

	@Autowired
	private HsmwBizUserService hsmwBizUserService;

	@Autowired
	private HsmwHtnUserService hsmwHtnUserService;

	@Autowired
	private HsmwTpspUserService hsmwTpspUserService;

	@Autowired
	private HsmwSaleUserService hsmwSaleUserService;


	/**
	 * 分页
	 *
	 * @param basePage
	 * @return
	 */
	@ApiOperation(value = "获取项目分页列表，参数： 审核状态 auditStatus 1: 审核中、2: 审核通过、3: 审核拒绝 ；项目名称或者施工单位名称：queryParam；提交时间：createTime  格式：yyyy-MM-dd HH:mm:ss  ", notes = "获取司机分页列表", produces = "application/json")
	@PostMapping("/getHsmwItemPage")
	public DataResponse getHsmwAuditPage(@RequestBody @Valid BasePage<HsmwItem> basePage) {
		IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
		HsmwItem hsmwItem = basePage.getRequestData();
		IPage<HsmwItem> data = hsmwItemService.getItemAuditPageInfo(page, hsmwItem);
		return DataResponse.success(data);
	}

	/**
	 * 查询租赁公司信息
	 *
	 * @return
	 */
	@ApiOperation(value = "查询租赁公司信息", notes = "查询租赁公司信息", produces = "application/json")
	@PostMapping("/findLeasingCompanyList")
	public DataResponse findLeasingCompanyList() {
		List<HsmwLeasingCompany> companies =hsmwLeasingCompanyService.list(new LambdaQueryWrapper<HsmwLeasingCompany>()
				.orderByDesc(HsmwLeasingCompany::getCreateTime));
		return new DataResponse(companies);
	}


	/**
	 * 查询项目下工长信息
	 *
	 * @return
	 */
	@ApiOperation(value = "查询项目下工长信息", notes = "查询项目下工长信息", produces = "application/json")
	@ApiImplicitParam(name = "itemId",value = "项目Id", dataType = "String")
	@PostMapping("/getHsmwItemById")
	public DataResponse getHsmwItemById(String itemId) {
		List<ItemForemanInfoVO> itemForemanInfoVOs = new ArrayList<>();
		HashMap param = new HashMap();
		param.put("itemId",itemId);
		List<HsmwHtnUser > foreList =hsmwForcemanItemMapper.selectForemanListByItemId(param);
		if(CollectionUtil.isNotEmpty(foreList)){
			for(HsmwHtnUser hsmwUser :foreList){
				ItemForemanInfoVO itemForemanInfoVO = new ItemForemanInfoVO();
				List<HsmwOrder> list = hsmwOrderService.list(new LambdaQueryWrapper<HsmwOrder>().eq(HsmwOrder::getCreateUser, hsmwUser.getId())
						.eq(HsmwOrder::getOrderStatus, OrderStatusEnum.COMPLETED.getValue()));

				Double sum = 0.00;
				for (HsmwOrder hsmwOrder : list) {
					if(hsmwOrder != null){
						sum+= Double.parseDouble(hsmwOrder.getForemanVolume());
					}
				}
				itemForemanInfoVO.setName(hsmwUser.getName());
				itemForemanInfoVO.setSumVolume(sum);
				itemForemanInfoVO.setUsername(hsmwUser.getUsername());
				itemForemanInfoVO.setItemIdentifyNum(list.size());
				itemForemanInfoVOs.add(itemForemanInfoVO);
			}
		}
		return new DataResponse(itemForemanInfoVOs);
	}

	/**
	 * 修改项目审核信息
	 *
	 * @param item
	 * @return
	 */
	@ApiOperation(value = "中控端 修改项目审核信息", notes = "修改项目审核信息", produces = "application/json")
	@PostMapping("/upadteItemInfo")
	public DataResponse upadteItemInfo(@RequestBody HsmwItem item) {
		try {
			hsmwItemService.updateById(item);
			return new DataResponse();
		}catch (Exception e){
			return  DataResponse.failure(CommonConstants.ResponseStatus.VALIDATE_FAILED.getCode(),"项目审核信息修改失败，请稍后重试！");
		}
	}

	/**
	 * @param
	 * @return
	 */
	@ApiOperation(value = "项目审核通过", notes = "审核通过", produces = "application/json")
	@PostMapping("/passHsmwAudit")
	public DataResponse passHsmwAudit(@RequestBody HsmwItem hsmwItem) {
		hsmwItemService.passHsmwAudit(hsmwItem);
		return new DataResponse(true);
	}

	/**
	 * @param form
	 * @return
	 */
	@ApiOperation(value = "司机 审核拒绝", notes = "审核拒绝  id、remark：备注", produces = "application/json")
	@PostMapping("/refuseHsmwAudit")
	public DataResponse refuseHsmwAudit(@RequestBody JSONObject form) {
		hsmwItemService.refuseHsmwAudit(form.getStr("key"), form.getStr("remark"));
		return new DataResponse(true);
	}


	/**
	 * @param form
	 * @return
	 */
	@ApiOperation(value = "根据项目ID 获取项目的详情信息", notes = "根据项目ID 获取项目的详情信息", produces = "application/json")
	@PostMapping("/getItemDetail")
	public DataResponse getItemDetail(@RequestBody JSONObject form) {
		ItemDetailInfoVO  itemDetailInfoVO = hsmwItemService.getItemDetail(form.getStr("itemId"));
		return new DataResponse(itemDetailInfoVO);
	}


	/*
	 * 分页
	 * @param basePage
	 * @return
	 */
	@ApiOperation(value = "获取项目的 按照月和年统计 数据 ", notes = "获取司机分页列表", produces = "application/json")
	@ApiImplicitParam(name = "type",value = "统计纬度 月 month  年 year",dataType = "String")
	@PostMapping("/getConcreteStatistics")
	public DataResponse getConcreteStatistics(@RequestBody ConcreteCountTypeVO concreteCountTypeVO) {
		if(StringUtils.isBlank(concreteCountTypeVO.getMonth())){
			return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的月份为空！");
		}
		if(StringUtils.isBlank(concreteCountTypeVO.getItemId())){
			return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的项目ID为空！");
		}
		HashMap data = hsmwConcretePlantInfoService.getItemStatistics(concreteCountTypeVO);
		return DataResponse.success(data);
	}



	/**
	 * 项目信息新增
	 *
	 * @param
	 * @return
	 */
	@ApiOperation(value = "中控项目信息新增", notes = "中控项目信息新增", produces = "application/json")
	@PostMapping("/saveItemInfo")
	public DataResponse addItemInfo(@RequestBody  HsmwItem  hsmwItem) {
		try {
			LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
			if(StringUtils.isBlank(hsmwItem.getId())){
				List<HsmwItem> items = hsmwItemService.list(new LambdaQueryWrapper<HsmwItem>()
						.eq(HsmwItem::getName,hsmwItem.getName()));
				if(CollectionUtil.isNotEmpty(items)){
					return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的项目名称已存在，请重新输入！");
				}
			}
			String identifyNum = CommonUtils.generateItemIdentifyNum();
			hsmwItem.setItemIdentifyNum(identifyNum);
			hsmwItem.setAuditStatus("2");
			List<HsmwHtnUser> users = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
					.eq(HsmwHtnUser::getUsername,hsmwItem.getUserPhone()));
			if(CollectionUtil.isNotEmpty(users)){
				HsmwHtnUser user = users.get(0);
				hsmwItem.setCreateUser(user.getId());
			}else{
				HsmwHtnUser hsmwUser = new HsmwHtnUser();
				hsmwUser.setType(UserTypeEnum.PM.getValue());
				hsmwUser.setEnabled(true);
				hsmwUser.setCreateUser(currentUser.getId());
				hsmwUser.setName(hsmwItem.getCreateName());
				hsmwUser.setUsername(hsmwItem.getUserPhone());
				hsmwHtnUserService.save(hsmwUser);
				HsmwHtnUser user = hsmwHtnUserService.findByUsername(hsmwItem.getUserPhone());
				hsmwItem.setCreateUser(user.getId());
			}
			hsmwItemService.save(hsmwItem);
			HashMap result = new HashMap();
			result.put("itemIdentifyNum",identifyNum);
			return new DataResponse(result);
		}catch (Exception e){
			e.printStackTrace();
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"项目信息新增失败，请联系管理员！");
		}
	}


	/**
	 * 项目信息修改
	 *
	 * @param
	 * @return
	 */
	@ApiOperation(value = "项目信息修改", notes = "项目信息修改", produces = "application/json")
	@PostMapping("/updateItemInfo")
	public DataResponse updateItemInfo(@RequestBody HsmwItem hsmwItem){

		LoginUser currentUser = currentHsmwUserUtils.getCurrentUserInfo();
		if(hsmwItem == null){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"传递参数错误，强检查！");
		}

		if(StringUtils.isBlank(hsmwItem.getId())){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"id不可为空");
		}

		List<HsmwPmUser> users = hsmwPmUserService.list(new LambdaQueryWrapper<HsmwPmUser>()
				.eq(HsmwPmUser::getUsername,hsmwItem.getUserPhone()));


		if(CollectionUtil.isNotEmpty(users)){
			HsmwPmUser user = users.get(0);
			hsmwItem.setCreateUser(user.getId());
		}else{
			if(hsmwItem.getUserPhone() != null){
				HsmwPmUser hsmwUser = new HsmwPmUser();
				hsmwUser.setType(UserTypeEnum.PM.getValue());
				hsmwUser.setEnabled(true);
				hsmwUser.setCreateUser(currentUser.getId());
				hsmwUser.setName(hsmwItem.getCreateName());
				hsmwUser.setUsername(hsmwItem.getUserPhone());
				hsmwPmUserService.save(hsmwUser);
				HsmwPmUser user = hsmwPmUserService.findByUsername(hsmwItem.getUserPhone());
				hsmwItem.setCreateUser(user.getId());
			}
		}
		boolean update = hsmwItemService.updateById(hsmwItem);
		if(update){
			return new DataResponse(CommonConstants.ResponseStatus.SUCCESS,"修改成功");
		}
		return new DataResponse(CommonConstants.ResponseStatus.FAIL,"修改失败");
	}

	/**
	 *
	 * 项目删除
	 *
	 */
	@ApiOperation(value = "根据项目id删除项目", notes = "根据项目id删除项目", produces = "application/json")
	@PostMapping("/deleteItemInfoById")
	public DataResponse deleteItemInfoById(@RequestBody GetObjectByIdForm form){
		if(form.getKey() == null){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"id不能为空");
		}
		try {
			boolean del = hsmwItemService.removeById(form.getKey());
			if(del){
				return new DataResponse(CommonConstants.ResponseStatus.SUCCESS,"删除成功");
			}
			//删除项目以后 需要将 与改项目关联关系给删除
			hsmwForcemanItemMapper.delete(new LambdaQueryWrapper<HsmwForcemanItem>()
					.eq(HsmwForcemanItem::getItemId,form.getKey()));
			return new DataResponse();
		}catch (Exception e){
			e.printStackTrace();
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"删除失败");
		}
	}

	/**
	 * @param form
	 * @return
	 */
	@ApiOperation(value = "根据项目ID 获取可用搅拌站", notes = "根据项目ID 获取项目的详情信息", produces = "application/json")
	@PostMapping("/getAviablePlantInfos")
	public DataResponse getAviablePlantInfos(@RequestBody JSONObject form) {
		List<HsmwConcretePlantInfo>  concretePlantInfos  = hsmwConcretePlantInfoService.getAviablePlantInfos(form.getStr("itemId"));
		return new DataResponse(concretePlantInfos);
	}


	/**
	 * @param plantInfoAddVO
	 * @return
	 */
	@ApiOperation(value = "项目添加搅拌站", notes = "根据项目ID 获取项目的详情信息", produces = "application/json")
	@PostMapping("/addPlantInfos")
	public DataResponse addPlantInfos(@RequestBody PlantInfoAddVO plantInfoAddVO) {
		if(StringUtils.isBlank(plantInfoAddVO.getItemId())){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"项目id不能为空");
		}
		if(StringUtils.isNull(plantInfoAddVO.getPlantIds()) || plantInfoAddVO.getPlantIds().length==0){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"搅拌站ids不能为空");
		}
		hsmwConcretePlantInfoService.addPlantInfos(plantInfoAddVO);
		return new DataResponse();
	}





	/**
	 * @param
	 * @return
	 */
	@ApiOperation(value = "混天凝APP 项目管理 根据项目ID 获取项目的详情信息", notes = "根据项目ID 获取项目的详情信息", produces = "application/json")
	@PostMapping("/getItemDetailByItemId")
	public DataResponse getItemDetailByItemId(String itemId) {
		if(StringUtils.isBlank(itemId)){
			return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的项目ID为空！");
		}
		HashMap itemDetailInfoVO = hsmwItemService.getItemDetailById(itemId);
		return new DataResponse(itemDetailInfoVO);
	}


	/*
	 * 分页
	 * @param basePage
	 * @return
	 */
	@ApiOperation(value = "混天凝APP 项目管理  获取项目的 按照月和年统计 数据 ", notes = "获取司机分页列表", produces = "application/json")
	@ApiImplicitParam(name = "type",value = "统计纬度 月 month  天 day",dataType = "String")
	@PostMapping("/getItemCountStatistics")
	public DataResponse getItemCountStatistics(@RequestBody ItemCountTypeVO itemCountTypeVO) {
		if(StringUtils.isBlank(itemCountTypeVO.getItemId())){
			return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的项目为空！");
		}
		if(StringUtils.isBlank(itemCountTypeVO.getType())){
			return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的查询类型为空！");
		}
		HashMap data = hsmwItemService.getItemStatisticsByItemId(itemCountTypeVO);
		return DataResponse.success(data);
	}



	/**
	 * @param
	 * @return
	 */
	@ApiOperation(value = "根据项目ID 获取项目的简单信息", notes = "根据项目ID 获取项目的简单信息", produces = "application/json")
	@PostMapping("/getItemById")
	public DataResponse getItemById(String itemId) {
		HsmwItem   itemDetailInfoVO = hsmwItemService.getHsmwItemById(itemId);
		return new DataResponse(itemDetailInfoVO);
	}


}
